package config

import (
	"fmt"
	"github.com/jinzhu/configor"
	jsoniter "github.com/json-iterator/go"
	"time"
)

var file = "config.yaml" // 配置文件名

var Config config

type Mysql struct {
	Host     string
	Port     int
	UserName string
	PassWord string
	DbName   string
	Debug    bool
	Salve    bool
}

type Mongo struct {
	Host     string
	Port     int
	DBName   string
	AuthDB   string
	UserName string
	Password string
	Auth     bool
}

type Redis struct {
	Host     string
	Port     int
	PassWord string
	DB       int
	PoolSize int
}

type ES struct {
	URL string
}

type Server struct {
	ServiceName string // 服务名
	Environment string // 服务部署环境  可以是 local, dev, test, master （默认master）
}

type Web struct {
	Debug bool // gin是否开启debug模式
	Port  int  // 服务使用端口
}

type config struct {
	Redis  Redis
	Mongo  Mongo
	Mysql  Mysql
	ES     ES
	Server Server
	Web    Web
}

// 加载配置文件
func loadConfig() {
	err := configor.Load(&Config, file)
	if err != nil {
		panic(err)
	}
	ToJson := func(v interface{}) string {
		bs, err := jsoniter.MarshalIndent(v, "", "   ")
		if err != nil {
			return ""
		}
		return string(bs)
	}

	fmt.Printf("[%s] "+time.Now().Format("2006-01-02 15:04:05")+"%s"+"\r\n",
		"Config",
		fmt.Sprintf("%s\n%s\n%v\n%s\n",
			"Init Load Config Success",
			"-----------------------------------",
			ToJson(Config),
			"-----------------------------------",
		),
	)
}

func Init() {
	loadConfig()
}
